package cn.edu.sanxiau.www.control;

import java.util.HashMap;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import cn.edu.sanxiau.www.model.Permission;
import cn.edu.sanxiau.www.model.User;
import frame.utils.control.BaseControl2;

public class LoginControl extends BaseControl2 {

	/**
	 * 
	 */
	private static final long serialVersionUID = 6474272139574527771L;

	// 登录
	public String login(HttpServletRequest req, HttpServletResponse resp) {
		// 1、接受数据
		String userName = req.getParameter("userName");
		String password = req.getParameter("password");
		// #############################业务###############################
		// 3、调用业务
		// 领域模型装数据
		User user = new User();
		user.setUserName(userName);
		user.setPassword(password);

		// 分析具体业务
		User user_db = userService.queryUserByUser(user);
		// System.out.println("-------------" + user_db);

		// #############################业务###############################
		if (user_db != null) {
			if (userName.equals(user_db.getUserName())) {
				// 登录用户信息保存到session
				HttpSession session = req.getSession();
				session.setAttribute("USER_DB", user_db);
				// 提示信息
				req.setAttribute("message", "登录成功！！！");
				// 2、跳转页面

				return "view/system/main/main.jsp";
			} else {
				// 提示信息
				req.setAttribute("message", "用户名或密码错误，请重新输入！");
				// 2、跳转页面
				return "login.jsp";
			}

		} else {
			// 2、跳转页面
			return "login.jsp";
		}
	}

	// 登录
	public String left(HttpServletRequest req, HttpServletResponse resp) {

		// ----------------- 权限菜单数据 -----------------
		HttpSession session = req.getSession();
		User user_db = (User) session.getAttribute("USER_DB");
		
		
		int userId = user_db.getUserId();

		// 2、实例化HashMap
		HashMap<Integer, List<Permission>> menuLvMap = new HashMap<>();
		// 1、登录用户信息ID,查询拥有的菜单
		List<Permission> firstLvMenuList = permissionService.queryUser_xz_permissionByUserId(userId);
		for (Permission permission : firstLvMenuList) {
			int pId = permission.getPermissionId();
			List<Permission> permissionSelectedListSon = permissionService.queryXZPermissionAllSonByPId(pId);
			for (Permission permission2 : permissionSelectedListSon) {
				System.out.println(permission2);
			}
			// 维护父节点和子节点关系
			menuLvMap.put(pId, permissionSelectedListSon);
		}
		req.setAttribute("firstLvMenuList", firstLvMenuList);
		req.setAttribute("menuLvMap", menuLvMap);
		// ----------------- 权限菜单数据 -----------------

		return "view/system/main/left.jsp";
	}
}
